class UserDao {
    constructor(pool) {
        this.pool = pool;
    }

    async register(user_name, user_pwd, user_phone, user_email, user_address, role_name, nick_name) {
        const sql = `
            INSERT INTO users(
                user_id,
                user_name,
                user_pwd,
                user_phone,
                user_email,
                user_address,
                role_name,
                nick_name
            ) VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?)
        `;
        return await this.pool.execute(sql, [
            user_name,
            user_pwd,
            user_phone,
            user_email,
            user_address,
            role_name,
            nick_name
        ]);
    }
    
    // 新方法：通过用户名获取用户信息（包含密码）
    async getUserByUsername(user_name) {
        const sql = "SELECT * FROM users WHERE user_name = ?";
        const [rows] = await this.pool.execute(sql, [user_name]);
        
        // 如果找到用户，返回用户数据
        if (rows.length > 0) {
            return rows[0];
        }
        
        // 如果没有找到用户，返回 null
        return null;
    }
    
    // 获取用户角色
    async getUserRole(userId) {
        const sql = "SELECT role_name FROM users WHERE user_id = ?";
        const [rows] = await this.pool.execute(sql, [userId]);
        if (rows.length > 0) {
        return rows[0].role_name; // 返回用户角色
        } else {
        throw new Error("用户角色查询失败");
        }
    }

    // 获取用户部分信息
    async getUserInfo(userId) {
        const sql = "SELECT user_name, user_address,role_name,nick_name FROM users WHERE user_id = ?";
        const [rows] = await this.pool.execute(sql, [userId]);
        if (rows.length > 0) {
            return rows[0]; // 返回用户角色
        } else {
            throw new Error("用户角色查询失败");
        }
    }

    // 检查用户名是否已存在
    async checkUserNameExists(user_name) {
        const sql = "SELECT COUNT(*) as count FROM users WHERE user_name = ?";
        const [rows] = await this.pool.execute(sql, [user_name]);
        return rows[0].count > 0;
    }

    // 检查昵称是否已存在
    async checkNickNameExists(nick_name) {
        const sql = "SELECT COUNT(*) as count FROM users WHERE nick_name = ?";
        const [rows] = await this.pool.execute(sql, [nick_name]);
        return rows[0].count > 0;
    }

    // 更新用户密码
    async updateUserPassword(user_id, hashed_password) {
        const sql = "UPDATE users SET user_pwd = ? WHERE user_id = ?";
        return await this.pool.execute(sql, [hashed_password, user_id]);
    }

}

module.exports = UserDao;